import os
from datetime import datetime


class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def __str__(self):
        return f"学生 {self.name} 的成绩是 {self.score}"


class xitong:
    Mima = "123456"  # 管理员密码
    data_file = "students.txt"  # 数据存储文件

    def __init__(self):
        self.students = []
        self.load_from_file()

    def save_to_file(self):
        """保存数据到文本文件"""
        with open(self.data_file, "w", encoding="utf-8") as f:#简化代码，with可以对文件进行自动关闭 ，as f可以赋值给变量f
            for student in self.students:
                f.write(f"{student.name},{student.score}\n")

    def load_from_file(self):
        """从文本文件加载数据"""
        # os.path.exists()函数用于判断文件是否存在
        if os.path.exists(self.data_file):
            with open(self.data_file, "r", encoding="utf-8") as f:#简化代码，with可以对文件进行自动关闭 ，as f可以赋值给变量f
                for line in f:
                    name, score = line.strip().split(',')
                    self.students.append(Student(name, float(score)))#将数据添加到列表中

    def add_student(self, name, score):
        new_student = Student(name, score)
        self.students.append(new_student)
        self.save_to_file()
        print(f"学生 {name} 的记录已添加.")

    def delete_student(self, name):
        for i, student in enumerate(self.students):
            if student.name == name:
                del self.students[i]
                self.save_to_file()
                print(f"学生 {name} 的记录已删除.")
                return
        print(f"未找到学生 {name}.")

    def C(self, name):
        for student in self.students:
            if student.name == name:
                print(student)
                return
        print(f"未找到学生 {name}.")

    def D(self, name, new_score):
        if self.admin_verify():
            for student in self.students:
                if student.name == name:
                    student.score = new_score
                    self.save_to_file()
                    print(f"学生 {name} 的成绩已更新为 {new_score}")
                    return
            print(f"未找到学生 {name}.")

    def E(self):
        """显示所有学生信息"""
        print("\n【所有学生记录】")
        if not self.students:
            print("当前没有学生记录")
            return

        total = sum(s.score for s in self.students)
        print(f"{'序号':<5}{'姓名':<10}{'成绩':<6}")
        for idx, student in enumerate(self.students, 1):
            print(f"{idx:<5}{student.name:<10}{student.score:<6.1f}")
        print(f"\n总记录数: {len(self.students)} 条")
        print(f"平均成绩: {total / len(self.students):.1f}")

    def admin_verify(self):
        """管理员身份验证"""
        password = input("请输入管理员密码: ")
        return password == self.Mima

    def run(self):
        print(f"\n今天是: {datetime.now().strftime('%Y年%m月%d日 %A')}")
        while True:
            print("\n学生成绩管理系统")
            print("1. 添加学生记录")
            print("2. 删除学生记录")
            print("3. 查找学生记录")
            print("4. 修改学生记录")
            print("5. 显示所有记录")
            print("6. 退出系统")

            choice = input("请选择操作 (1-6): ")

            if choice == '1':
                name = input("请输入学生姓名: ")
                score = float(input("请输入学生成绩: "))
                self.add_student(name, score)
            elif choice == '2':
                name = input("请输入要删除的学生姓名: ")
                self.delete_student(name)
            elif choice == '3':
                name = input("请输入要查找的学生姓名: ")
                self.C(name)
            elif choice == '4':
                if self.admin_verify():
                    name = input("请输入要修改的学生姓名: ")
                    new_score = float(input("请输入新的成绩: "))
                    self.D(name, new_score)
            elif choice == '5':
                self.E()
            elif choice == '6':
                print("感谢使用学生成绩管理系统!")
                break
            else:
                print("无效的选择，请重新输入.")


if __name__ == "__main__":
    system = xitong()
    system.run()